<template>
    <div class="labella_group_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
        <div class="handle-box">
            <el-button v-auth="'ADD_PULL_GROUP'" type="primary" @click="handleAdd">新建拉群</el-button>
        </div>
        <ZwTable
            ref="tableRef"
            class="table-box"
            :tab-h="`calc(100vh - 370px)`"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select-all="onSelectAll"
            @select="onSelect"></ZwTable>
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="ZWDeletdialogRef" @submit="confirmDel" />
        <!-- 客户明细 -->
        <ZWDrawer ref="DrawerRef" @close="showBox = false">
            <DetailHeader v-if="showBox" :id="nowItemInfo.id"></DetailHeader>
            <el-tabs v-model="activeName" type="card" class="demo-tabs">
                <el-tab-pane label="群发记录" name="first">
                    <Members
                        v-if="activeName == 'first' && showBox"
                        :pull_id="nowItemInfo.id"
                        :option="option"
                        @search="search" />
                </el-tab-pane>
                <el-tab-pane label="成员邀请" name="second">
                    <Massrecord
                        v-if="activeName == 'second' && showBox"
                        :pull_id="nowItemInfo.id"
                        :option="option"
                        @search="search" />
                </el-tab-pane>
            </el-tabs>
        </ZWDrawer>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'LABEL_LA_GROUP' });
</script>

<script lang="tsx" setup>
import DetailHeader from './components/DetailHeader.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { reactive, ref, onMounted, onActivated, computed, nextTick } from 'vue';
import { customerRemove, getAutoGroupList } from '@/api/customerCenter/labellagroup';
import { ElMessage, ElButton, ElTooltip } from 'element-plus';

import { IsNotEmpty, getSetionId } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import router from '@/router';
import { useStore } from '@/store';
import ZWDrawer from './components/ZWDrawer.vue';
import Massrecord from './components/Massrecord.vue';
import Members from './components/Members.vue';
import dayjs from 'dayjs';

const activeName = ref('first');

const nowItemInfo = ref({}); //当前查看那个数据详情
const showBox = ref(false);
const store = useStore();
const ZWDeletdialogRef = ref(null);
const removeId = ref(0);
const DrawerRef = ref(null);
const StaffInfoRef = ref(null);
const tableRef = ref(null);
const defaultParams = reactive({
    name: '',
    groupchat_id: 0, //群聊 -1全部
    create_time: []
});

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '拉群任务',
            name: 'name',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入任务名称'
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});
const tableOption = [
    {
        prop: 'name',
        label: '任务名称',
        minWidth: 200
    },
    {
        label: '员工归属',
        width: 250,
        render({ row, column, index }) {
            const defaultSlots = () => (
                <div>
                    <div>{row.belong_to_json?.work_user?.length}个员工</div>
                </div>
            );
            const defaultSlots2 = () => (
                <div>
                    <div class="box_item ml20">{row.belong_to_json?.work_department?.length}个部门</div>
                </div>
            );
            const defaultContent = () => <div> {getSetionId('name', row.belong_to_json?.work_user).join('、')}</div>;
            const defaultContent2 = () => (
                <div>{getSetionId('name', row.belong_to_json?.work_department).join('、')}</div>
            );
            return (
                <div>
                    <div vShow={row.belong_to_type == 1}>全部成员</div>
                    <div vShow={row.belong_to_type != 1} class="emplyee_box emplyee_all">
                        <span vShow={row.belong_to_json?.work_user?.length > 0} style={{ ['margin-right']: '0px' }}>
                            <ElTooltip
                                class="box_item"
                                effect={'light'}
                                placement="top-start"
                                vSlots={{ default: defaultSlots, content: defaultContent }}></ElTooltip>
                        </span>
                        <div vShow={!(row.belong_to_json?.work_user?.length > 0)} class="box_item ml20">
                            {row.belong_to_json?.work_user?.length}个员工
                        </div>
                        <span vShow={row.belong_to_json?.work_department?.length > 0} class="ml20">
                            <ElTooltip
                                class="box_item"
                                effect={'light'}
                                placement="top-start"
                                vSlots={{ default: defaultSlots2, content: defaultContent2 }}></ElTooltip>
                        </span>
                        <div vShow={!(row.belong_to_json?.work_department?.length > 0)} class="box_item ml20">
                            {row.belong_to_json?.work_department?.length}个部门
                        </div>
                    </div>
                </div>
            );
        }
    },
    {
        label: '邀请入群',
        minWidth: 200,
        render({ row, column, index }) {
            return (
                <>
                    <div class="emplyee_box" vShow={IsNotEmpty(row.groupchat)}>
                        <div vShow={row.groupchat.length > 3}>
                            {row.groupchat.map((item: any) => {
                                return (
                                    <div title={groupMembers(row.groupchat)}>
                                        {item.name}({item.member_nums})人
                                    </div>
                                );
                            })}
                        </div>
                        <div vShow={!(row.groupchat.length > 3)}>
                            {row.groupchat.map((item: any) => {
                                return (
                                    <div>
                                        {item.name}（{item.member_nums}）人
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                    <div vShow={!IsNotEmpty(row.groupchat)}>--</div>
                </>
            );
        }
    },
    {
        label: '发送客户情况',
        width: 150,
        render({ row, column, index }) {
            return (
                <div>
                    <div vShow={IsNotEmpty(row)}>
                        <div>预计发送 {row.expected_delivery_num} 人</div>
                        <div>成功发送 {row.deliver_num} 人</div>
                    </div>
                    <div vShow={!IsNotEmpty(row)}>--</div>
                </div>
            );
        }
    },
    {
        label: '客户入群情况',
        width: 150,
        render({ row, column, index }) {
            return (
                <div>
                    <div vShow={IsNotEmpty(row)}>
                        <div>已入群 {row.join_groupchat_num} 人</div>
                        <div>未入群 {row.not_join_groupchat_num} 人</div>
                    </div>
                    <div vShow={!IsNotEmpty(row)}>--</div>
                </div>
            );
        }
    },
    {
        prop: 'created_name',
        label: '创建人',
        width: 200
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 200,
        render({ row }) {
            return <span>{dayjs(row.created_at).format('YYYY-MM-DD HH:mm:ss')}</span>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 250,
        isOperate: true,
        render({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton size="small" onClick={() => handleDetails(index, row)} vAuth={'VIEW_CUSTOMER_DETAIL'}>
                        客户明细
                    </ElButton>
                    <ElButton size="small" onClick={() => handleLook(index, row)} vAuth={'VIEW'}>
                        查看
                    </ElButton>
                    <ElButton size="small" onClick={() => handleDel(index, row)} vAuth={'DEL'}>
                        删除
                    </ElButton>
                </div>
            );
        }
    }
];
const reset = (v?: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy(v);
    currentParams.value = null;
};
const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getAutoGroupList;
};
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const group_id = computed(() => {
    return store.getters['content/type'];
});

const formInline = ref({
    group_id: group_id.value
    // group_name: '',
    // create_time: []
});
const option = reactive([
    { label: '拉群任务', type: 'input', key: 'group_name', value: formInline.value.group_name },
    { label: '选择群聊', type: 'select' },
    { label: '创建时间', type: 'datePicker', key: 'create_time', value: formInline.value.create_time }
]);

const search = (data: any) => {
    currentParams.value = data;
    // let cteate_time = ''
    state.searchParams = deepCopy(data);

    // if (data.cteated_time && data.cteated_time.length == 2) {
    //   cteate_time = data.cteated_time[0] + '~' + data.cteated_time[1]
    // }
    // Object.assign(data, { cteate_time })
    formInline.value = { ...data };
};
// 入群的部门
const groupMembers = (data: any) => {
    let str = '';
    data.forEach((item: any) => {
        str += `${item.name}（${item.member_nums}）人 `;
    });
    return str;
};

// 删除
const handleDel = (index: number, row: any) => {
    ZWDeletdialogRef.value.appDialog.visible = true;
    ZWDeletdialogRef.value.content = '确定删除吗';
    removeId.value = row.id;
};
// 确定删除
const confirmDel = async () => {
    const res = await customerRemove({
        pull_id: removeId.value
    });
    ElMessage.success('删除成功');
    ZWDeletdialogRef.value.appDialog.visible = false;
    tableRef.value.reload();
};
//新建拉群
const handleAdd = () => {
    router.push('/customer/groupManage/labellagroup/creategroupchat');
};
// 查看
const handleLook = (index: number, row: any) => {
    router.push('/customer/groupManage/labellagroup/creategroupchat?look=true&&id=' + row.id + '&type=look');
};
onMounted(() => {
    store.dispatch('content/changeType', 21);
});
//查看明细
const handleDetails = (index: number, val: any) => {
    activeName.value = 'first';
    showBox.value = true;
    nowItemInfo.value = val;
    DrawerRef.value.title = `【${val.name}】明细`;
    DrawerRef.value.drawer = true;
    DrawerRef.value.width = 1000;
    DrawerRef.value.isShow = false;
};

onActivated((val: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
    formInline.value = { ...currentParams.value };
});
</script>

<style scoped lang="scss">
.labella_group_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.member {
    margin-top: 10px;
}

.btn_opc {
    margin-right: 10px;
}

.btn_opc.el-button + .el-button {
    margin-left: 0;
}

:deep(.emplyee_box) {
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    word-break: break-all;

    .box-item {
        width: 400px;
    }
}

:deep(.box_item) {
    display: inline-block;
}

.ml20 {
    margin-left: 20px;
}

.btn-wrap {
    display: flex;
}

.gc-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 18px 18px;
    font-size: 14px;
    color: #33302d;
}

.container {
    background-color: #fff;
    height: 120px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 16px;
    border: 1px solid #eaeaea;
    border-bottom: 1px solid #ffc69e;

    .container-item {
        text-align: center;

        .title {
            font-size: 16px;
            font-weight: 400;
            color: #35383a;
            margin-bottom: 6px;

            // display: flex;
            // align-items: center;
        }

        .title-text {
            font-size: 36px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #ff6b00;
            line-height: 36px;
        }
    }

    .line-item {
        width: 1px;
        height: 60px;
        background-color: #f0f0f0;
        border-radius: 1px;
    }
}

.handle-box {
    text-align: right;
}

.demo-tabs {
    margin-top: 16px;
}
</style>
